package com.zmj.sy.mom.srv.aps.service;

import cn.hutool.core.collection.CollUtil;
import com.zmj.sy.mom.srv.aps.bean.entity.base.BaseEntity;
import com.zmj.sy.mom.srv.aps.bean.entity.order.*;
import com.zmj.sy.mom.srv.aps.bean.entity.resource.DictData;
import com.zmj.sy.mom.srv.aps.bean.entity.third.SinoCamPushDrawing;
import com.zmj.sy.mom.srv.aps.bean.entity.third.SinoCamPushPlan;
import com.zmj.sy.mom.srv.aps.config.ProjectConfig;
import com.zmj.sy.mom.srv.aps.mapper.*;
import com.zmj.sy.mom.srv.aps.utils.JsonUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class FixService {


    private final OrderMapper orderMapper;
    private final ApsOrderMapper apsOrderMapper;
    private final ApsWorkOrderMapper apsWorkOrderMapper;
    private final OrderBomMapper orderBomMapper;
    private final ProjectConfig projectConfig;
    private final ApsWorkDetailMapper apsWorkDetailMapper;
    private final SinoCamPushDrawingMapper sinoCamPushDrawingMapper;
    private final SinoCamPushPlanMapper sinoCamPushPlanMapper;
    private final OrderPartMapper orderPartMapper;
    private final ImportMbdDxfMapper importMbdDxfMapper;
    private final DictDataMapper dictDataMapper;
    @Value("${project.feign.dxf-download}")
    private String dxfDownload;


    @Transactional
    public void nestPush(Integer orderId) {

        // 获取需要切割的工序
        List<String> phaseCodeList = projectConfig.getCuttingProcess();

        // 获取所有需要切割的零件
        List<ApsWorkDetail> apsWorkDetailList = apsWorkDetailMapper.lambdaQuery()
                .eq(ApsWorkDetail::getOrderId, orderId)
                .eq(ApsWorkDetail::getStatus, 2)
                .in(ApsWorkDetail::getPhaseCode, phaseCodeList)
                .list();

        Order order = orderMapper.selectById(orderId);

        List<SinoCamPushDrawing> pushDrawList = sinoCamPushDrawingMapper.lambdaQuery().eq(SinoCamPushDrawing::getOrderId, orderId).list();
        List<SinoCamPushPlan> pushPlanList = sinoCamPushPlanMapper.lambdaQuery().eq(SinoCamPushPlan::getOrderId, orderId).list();
        Map<String, SinoCamPushDrawing> pushPartMap = pushDrawList.stream().collect(Collectors.toMap(e -> e.getPartId(), Function.identity()));

        // 修复 零件推送
        List<ApsOrder> apsOrders = apsOrderMapper.lambdaQuery().eq(ApsOrder::getOrderId, orderId).list();
        Map<Integer, ApsOrder> apsOrderIdMap = apsOrders.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        // 取 ID
        List<ApsWorkOrder> apsWorkOrders = apsWorkOrderMapper.selectBatchIds(apsWorkDetailList.stream().map(ApsWorkDetail::getApsWorkOrderId).distinct().collect(Collectors.toList()));
        Map<Integer, ApsWorkOrder> apsWorkOrderIdMap = apsWorkOrders.stream().collect(Collectors.toMap(ApsWorkOrder::getId, Function.identity()));

        // 取 PID
        List<ApsWorkOrder> parentApsWorkOrders = apsWorkOrderMapper.selectBatchIds(apsWorkDetailList.stream().map(ApsWorkDetail::getApsWorkOrderPid).distinct().collect(Collectors.toList()));
        Map<Integer, ApsWorkOrder> apsWorkOrderPidMap = parentApsWorkOrders.stream().collect(Collectors.toMap(ApsWorkOrder::getId, Function.identity()));

        List<OrderBom> orderBomList = orderBomMapper.lambdaQuery().in(OrderBom::getId, apsWorkOrders.stream().map(ApsWorkOrder::getBomId).distinct().collect(Collectors.toList())).list();
        Map<Integer, OrderBom> orderBomMap = orderBomList.stream().collect(Collectors.toMap(BaseEntity::getId, Function.identity()));

        List<OrderPart> orderPartList = new ArrayList<>();
        if(CollUtil.isNotEmpty(apsWorkOrders)){
            orderPartList = orderPartMapper.lambdaQuery().eq(OrderPart::getPlmId, apsWorkOrders.stream().map(ApsWorkOrder::getPlmId).collect(Collectors.toList())).list();
        }

        Map<String, OrderPart> orderPartMap = orderPartList.stream().collect(Collectors.toMap(OrderPart::getPlmId, Function.identity()));

        List<ImportMbdDxf> importMbdDxfList = importMbdDxfMapper.lambdaQuery().in(ImportMbdDxf::getPlmid, orderBomList.stream().map(OrderBom::getPlmId).distinct().collect(Collectors.toList())).list();
        Map<String, ImportMbdDxf> mbdDxfMap = importMbdDxfList.stream().collect(Collectors.toMap(ImportMbdDxf::getPlmid, Function.identity(), (a, b) -> b));


        for (ApsWorkOrder apsWorkOrder : apsWorkOrders) {
//            ApsWorkOrder apsWorkOrder = apsWorkOrderIdMap.get(apsWorkDetail.getApsWorkOrderId());
            if (pushPartMap.get(apsWorkOrder.getPlmId()) != null) {
                continue;
            }

            SinoCamPushDrawing pushDraw = new SinoCamPushDrawing();

            pushDraw.setOrderId(orderId);
            pushDraw.setFactoryIdk("170");
            pushDraw.setProjectId(order.getConstructNo());
            pushDraw.setPartId(apsWorkOrder.getPlmId());
            pushDraw.setPartName(apsWorkOrder.getMaterName());
            pushDraw.setPartType(1);
            pushDraw.setProductId(order.getPlmId());
            pushDraw.setUniMaterCode(order.getId() + "#" + apsWorkOrder.getPlmId());
            pushDraw.setSuspensionStatus(0);
            pushDraw.setVersionNum(1L);
//            pushDraw.setType(1);
            pushDraw.setStatus(1);
            pushDraw.setDrawStatus(1);
            pushDraw.setPartStatus(1);

            OrderBom bom = orderBomMap.get(apsWorkOrder.getBomId());
            String[] split = bom.getStandards().split("δ");

            pushDraw.setNorm(bom.getStandards());
            if (!StringUtils.hasText(bom.getTexture())) {
                pushDraw.setTexture(plateTextureReplace(split[0].trim()));
            } else {
                pushDraw.setTexture(plateTextureReplace(bom.getTexture()));
            }
            if (bom.getMaterHigh() == null) {
                pushDraw.setThickNess(new BigDecimal(split[1].trim()));
            } else {
                pushDraw.setThickNess(new BigDecimal(bom.getMaterHigh()));
            }

            String code = bom.getPlmId();
            if (code.endsWith("_170")) {
                code = code.substring(0, code.indexOf("_170"));
            }
            ImportMbdDxf mbdDxf = mbdDxfMap.get(code);

            if (!ObjectUtils.isEmpty(mbdDxf)) {
                pushDraw.setFilePath(dxfDownload + mbdDxf.getPath());
                pushDraw.setChartId(mbdDxf.getDocNumber());
                pushDraw.setDrawVersion(mbdDxf.getDocVersion());
                pushDrawList.add(pushDraw);
            } else {
                pushDraw.setStatus(5);
                pushDraw.setErrorMsg("未查询到下料图");
                pushDrawList.add(pushDraw);
            }
        }

        System.out.println(JsonUtils.toJsonString(pushDrawList));

    }

    public String plateTextureReplace(String texture) {
        List<DictData> dataList = dictDataMapper.plateTextureReplace();
        Map<String, String> dataMap = dataList.stream().collect(Collectors.toMap(DictData::getDictLabel, DictData::getDictValue));
        return dataMap.getOrDefault(texture, texture);
    }

}
